#include "dataStructuresHeader.h"
#include "nAryTree.h"
int createnAryTree(int iterDescriptors, descriptors desc[] )
{
	int ret=0;
	/*printf("In nary \n");
	
	//traversenAryTree(nAryRoot);
	if(nAryRoot!=NULL)
		//printf("%s\n",nAryRoot->name);
		traversenAryTree(nAryRoot);*/
	nAryRoot = NULL;
	char *str[iterDescriptors];
	nAryRoot=(nAryNode*)malloc(sizeof(nAryNode));
	nAryNode *current;
	nAryNode *temp;
	nAryRoot->name="/";
	nAryRoot->child=NULL;
	nAryRoot->sibling=NULL;
	char *tokens = NULL;
	int child=0; //whether a node is direct child(0) or sibling(1) of the child of parent..
	int found=0; //whether a token is found(0 if not found)
	int i=0;
	int maxFileDescriptors=mh->maxDescriptors;
	for(i=0;i<iterDescriptors;i++)
	{
		if(desc[i].type!='d' && desc[i].type!='f')
			continue;
		ret=-1;
		str[i]=(char*)malloc(sizeof(char)*50);
		//printf("Filename %s and Location %s\n",desc[i].fileName,desc[i].location);
		if(strcmp(desc[i].location,"/")==0)
			sprintf(str[i],"%s%s",desc[i].location,desc[i].fileName);
		else
			sprintf(str[i],"%s/%s",desc[i].location,desc[i].fileName);
		char *currStr=(char*)malloc(sizeof(char)*50);
		strcpy(currStr,str[i]);
		//printf("\n Current String is %s \n",currStr);
		tokens = strtok( currStr, "/" );
		current=(nAryNode*)malloc(sizeof(nAryNode));
		current=nAryRoot;
		while(tokens!=NULL)
		{
			//printf("Current token is %s\n",tokens);
			child=0;
			found=0;
			temp=(nAryNode*)malloc(sizeof(nAryNode));
			nAryNode *previous=(nAryNode*)malloc(sizeof(nAryNode));
			previous=current;
			//printf("\n Current node name is %s \n",current->name);
			current=current->child;
			while(current!=NULL)
			{
				child=1;
				previous=current;
				if(strcmp(current->name,tokens)!=0)
					current=current->sibling;
				else
				{
					found=1;
					break;
				}
			}
			if(found)
			{
				tokens = strtok( NULL, "/" );
				continue;
			}
			temp->name=tokens;
			temp->child=NULL;
			temp->sibling=NULL;
			if(child==0)
				previous->child=temp;
			else
			{
				while(previous->sibling!=NULL)
					previous=previous->sibling;
				previous->sibling=temp;
			}
			current=temp;
			//printf("Current node name is %s\n",current->name);
			tokens = strtok( NULL, "/" );
		}
		ret=0;
	}
	//printf("\n nAry Traversal");
	//traversenAryTree(nAryRoot);
	return ret; // successful creation of nAryTree
}
void traversenAryTree(nAryNode *nAryRoot)
{
	if(nAryRoot!=NULL)
	{
		traversenAryTree(nAryRoot->child);
		printf("\n %s \n",nAryRoot->name);
		traversenAryTree(nAryRoot->sibling);
	}
}
void freenAryTree(nAryNode *nAryRoot)
{
	if(nAryRoot!=NULL)
	{
		traversenAryTree(nAryRoot->child);
		traversenAryTree(nAryRoot->sibling);
		printf("\n Freeing %s \n",nAryRoot->name);
		//free(nAryRoot);
	}
}
